const axios = require('axios');
const cheerio = require('cheerio')
const iconv = require('iconv-lite');

// 云函数入口函数
exports.main = async (event, context) => {

  var isbn = event.isbn
  console.log(isbn)
  var url = 'http://search.dangdang.com/?key=' + isbn + '&sort_type=sort_sale_amt_desc#J_tab';
  let getResponse = await axios.get(url, {
    responseType: "arraybuffer"
  })
  let html = iconv.decode(getResponse.data, "gb2312");
  //console.log(html);
  var $ = cheerio.load(html)
  var name = $('.line1').find('.pic').attr('title')
  var imgurl = $('.line1').find('a').find('img').attr('src')
  var introduce = $('.line1').find('.name').find('a').text()
  var detail = $('.line1').find('.detail').text()
  var price = $('.line1').find('.search_now_price').text().replace("¥", '')
  price = parseFloat(price)
  var preprice = $('.line1').find('.search_pre_price').text().replace("¥", '')
  preprice = parseFloat(preprice)
  var discount = $('.line1').find('.search_discount').eq(1).text().replace(/ /g, '')
  var author = $('.line1').find('.search_book_author').find('a').eq(0).text()
  var time = $('.line1').find('.search_book_author').find('span').eq(1).text().replace("/", '').replace(/ /g, '')
  var cbname = $('.line1').find('.search_book_author').find('span').eq(2).text().replace("/", '').replace(/ /g, '')
  var list = {
    name: name,
    imgurl: imgurl,
    introduce: introduce,
    detail: detail,
    price: price,
    preprice: preprice,
    discount: discount,
    author: author,
    cbname: cbname,
    time: time,
    isbn:isbn
  }
  console.log(list)
  return list

}